package com.qfedu.wfx1.service.impl;

import com.qfedu.wfx1.mapper.GoodsMapper;
import com.qfedu.wfx1.po.WxbCustomer;
import com.qfedu.wfx1.po.WxbGood;
import com.qfedu.wfx1.po.WxbGoodSku;
import com.qfedu.wfx1.po.WxbGoodType;
import com.qfedu.wfx1.service.IGoodsService;
import com.qfedu.wfx1.service.IImagesService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service
public class GoodsService implements IGoodsService{
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private IImagesService iImagesService;

    @Override
    public List<WxbGoodType> queryGoodsType() {
        List<WxbGoodType> typeList = goodsMapper.queryGoodsType();
        return typeList;
    }

    @Override
    public void save(WxbGood wxbGood) throws Exception {
        String goodsId = UUID.randomUUID().toString();
        wxbGood.setGoodId(goodsId);
        List<WxbGoodSku> skuList = wxbGood.getSkuList();
        for (int i=0;i<skuList.size();i++){
            skuList.get(i).setSkuId(UUID.randomUUID().toString());
            skuList.get(i).setGoodId(goodsId);
        }
        goodsMapper.saveSku(skuList);
        goodsMapper.saveGoods(wxbGood);

        iImagesService.updateImageType("goods",goodsId,wxbGood.getGoodPicId());
        iImagesService.updateImageType("goods",goodsId,wxbGood.getGoodPic1Id());
        iImagesService.updateImageType("goods",goodsId,wxbGood.getGoodPic2Id());

    }

    @Override
    public WxbCustomer login(String username,String password) throws NullPointerException,AuthenticationException{
        if (username == null){
            throw new NullPointerException("username is null");
        }
        if (password == null){
            throw new NullPointerException("password is null");
        }
        WxbCustomer wxbCustomer = goodsMapper.checkCustomerLogin(username);
        if (wxbCustomer == null){
            throw new UnknownAccountException();
        }
        String salt = wxbCustomer.getCustomerName()+wxbCustomer.getCustomerId();
        Md5Hash md5Hash = new Md5Hash(password, salt);
        String hex = md5Hash.toHex();
        String loginPwd = wxbCustomer.getLoginPwd();
        if (!loginPwd.equals(hex)){
            throw new IncorrectCredentialsException();
        }
        return wxbCustomer;
    }

    @Override
    public List<WxbGood> queryGoods() {
        List<WxbGood> goodList = goodsMapper.queryGoods();
        return goodList;
    }
}
